package task

import (
	"fmt"
	"github.com/pkg/errors"
	"github.com/robfig/cron"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"os"
	"time"
	"xj.com/oos-data-service/config"
	"xj.com/oos-data-service/error_handler"
	"xj.com/oos-data-service/utils"
)

const (
	indexNamePrefix = "meta-"
	timeFormat      = "20060102"
)

type ClearTask struct {
}

func New() (c *ClearTask) {
	c = new(ClearTask)
	return c
}

func (c *ClearTask) clear() {
	now := time.Now()
	currentDate := now.Format(timeFormat)
	keepDays := config.Config.Clear.KeepDays
	if keepDays == -1 {
		log.Info("当前配置为永久保留，不进行清理文件及Es任务。")
		return
	}
	//清理这一天之前所有的文件及Es
	clearDate := now.AddDate(0, 0, -keepDays).Format(timeFormat)

	log.Info(fmt.Sprintf("开始清理日期为：%s的%d天前的文件及Es...", currentDate, keepDays))
	for _, writer := range config.Config.Writers {
		//查询当前已存在的所有文件
		dir := writer.Dir
		rd, err := ioutil.ReadDir(dir)

		error_handler.PrintError(err, "获取所有文件出错。")

		for _, fi := range rd {
			fileName := fi.Name()
			if fileName < clearDate {
				c.deleteFile(dir + string(os.PathSeparator) + fileName)
				c.deleteEs(fileName)
			}
		}
	}

}

func (c *ClearTask) getDeleteIndexUrl(timeStr string) string {
	return config.Config.Es.Url + "/" + indexNamePrefix + timeStr + "/?pretty"
}

func (c *ClearTask) Start() {
	cr := cron.New()
	err := cr.AddFunc(config.Config.Clear.Cron, c.clear)

	error_handler.PrintError(err, "开启文件及Es的定时清理任务失败")

	cr.Start()
}

func (c *ClearTask) deleteFile(filePath string) {
	log.Info("删除文件:", filePath)
	err := os.RemoveAll(filePath)
	error_handler.PrintError(err, "删除文件出错。")
}

func (c *ClearTask) deleteEs(indexName string) {
	log.Info("删除Es索引:", indexNamePrefix+indexName)
	resp, err := utils.GetRestRequest().Delete(c.getDeleteIndexUrl(indexName))
	if err != nil {
		log.Error(errors.WithMessage(err, "请求Es出错。"))
		log.Error(string(resp.Body()))
	}
}
